#!/bin/bash

# 生产环境启动脚本
APP_NAME="yunji-news"
PROFILE="prod"
PORT="8081"
JAR_NAME="news-1.0.0.jar"

# 定义端口号
port=$PORT

# 使用netstat命令找出监听指定端口的进程PID
pid=$(netstat -tulnp 2>/dev/null | grep ":$port" | awk '{print $7}' | cut -d'/' -f1 | head -1)

# 检查是否找到了PID
if [ -n "$pid" ]; then
    # 输出进程PID
    echo "Process ID listening on port $port: $pid"
    # 杀掉进程
    kill $pid
    echo "Process with PID $pid has been terminated."
    sleep 3
else
    echo "No process found listening on port $port."
fi

# 启动应用
echo "Starting $APP_NAME in $PROFILE environment on port $PORT..."

nohup java \
  -Xms1g \
  -Xmx2g \
  -XX:+UseG1GC \
  -XX:MaxGCPauseMillis=200 \
  -XX:+UnlockExperimentalVMOptions \
  -XX:+UseCGroupMemoryLimitForHeap \
  -Dserver.port=$PORT \
  -Dspring.profiles.active=$PROFILE \
  -Dfile.encoding=UTF-8 \
  -Djava.security.egd=file:/dev/./urandom \
  -jar $JAR_NAME \
  > app-$PROFILE.log 2>&1 &

echo "Started $APP_NAME with PID: $!"
echo "Log file: app-$PROFILE.log"
echo "To check status: tail -f app-$PROFILE.log"

# 检查启动状态
sleep 5
if ps -p $! > /dev/null; then
   echo "Application started successfully!"
else
   echo "Application failed to start. Check logs:"
   tail -20 app-$PROFILE.log
fi